﻿#include "ui_home.h"
#include "ui_ui_home.h"
#include "ui_info.h"
#include "ui_setMotor.h"
#include "cluster.h"
#include "ui_hmi.h"
#include "ui_setLocal.h"
#include "ui_setCluster.h"
#include "ui_about.h"
#include "ui_cmd.h"
#include "ui_dns.h"
#include "define.h"
#include <QDebug>
#include <QDomDocument>
#include <QtXml>
#include <QAction>
#include <QTimer>

uiHome::uiHome(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::uiHome)
{
    ui->setupUi(this);

//    this->m_statusText = new QLabel("等待连接...");
    this->m_motorRefrTime = new QLabel("");
//    ui->statusBar->addWidget(m_statusText);
    ui->statusBar->addWidget(m_motorRefrTime);


    /* 初始化线程类 */
    m_t = new QThread(this);

    // 重启就地控制器
    connect(ui->actionLocalReboot, &QAction::triggered, this, [=](){
        qDebug() << "重启就地控制器";
        int busId = ui->dropBus->currentIndex();
        QString maddr = ui->dropAddr->currentText();
        QString bus = ui->dropBus->currentText();
        QString sn = ui->sn->text();
        int click = QMessageBox::information(this, "重启就地控制器", QString("簇控制器[%1][%2:地址%3]\n就地控制器即将重启！").arg(sn).arg(bus).arg(maddr), "重启", "取消", "", 1);
        if (click == 0)
        {
            emit clusterReboot(sn, busId, maddr, CLUSTER_REBOOT);
        }
    });

    // 复位就地控制器
    connect(ui->actionLocalReset, &QAction::triggered, this, [=](){
        qDebug() << "复位就地控制器";
        int busId = ui->dropBus->currentIndex();
        QString maddr = ui->dropAddr->currentText();
        QString bus = ui->dropBus->currentText();
        QString sn = ui->sn->text();
        int click = QMessageBox::information(this, "复位就地控制器", QString("簇控制器[%1][%2:地址%3]\n就地控制器即将复位！").arg(sn).arg(bus).arg(maddr), "复位", "取消", "", 1);
        if (click == 0)
        {
            emit clusterReboot(sn, busId, maddr, CLUSTER_RESET);
        }
    });

    // HMI
    connect(ui->actionHMI, &QAction::triggered, this, [=](){
        qDebug() << "HMI";
        ShowHMI();
    });

    // 设置就地控制器
    connect(ui->actionSetLocal, &QAction::triggered, this, [=]() {
        qDebug() << "设置就地控制器";

        this->m_curLocalDev->setSn(ui->sn->text());
        uiSetLocal * Local = new uiSetLocal(this->m_curLocalDev);
        Local->setWindowModality(Qt::ApplicationModal);
        Local->setGeometry(this->x() + 150, this->y() + 50, Local->width(), Local->height());

        connect(Local, &uiSetLocal::setLocal, [=](QString xml){
            emit setLocal(xml);
        });

        Local->show();
    });

    // 设置簇控制器
    connect(ui->actionSetCluster, &QAction::triggered, this, [=](){
        qDebug() << "设置簇控制器";

        uiSetCluster * setC = new uiSetCluster(this->m_clus);
        setC->setWindowModality(Qt::ApplicationModal);
        setC->setGeometry(this->x() + 150, this->y() + 50, setC->width(), setC->height());

        connect(setC, &uiSetCluster::setCluster, [=](QString xml){
            qDebug() << "设置簇控制器";
            emit setCluster(xml);

            setC->close();
            setC->deleteLater();
        });

        setC->show();
    });

    // CMD
    connect(ui->actionCMD, &QAction::triggered, this, [=](){
        m_curLocalDev->setSn(ui->sn->text());

        // 读取信息
        ToolXml toolXml;
        QString xml = toolXml.makeGetCmdXml(m_curLocalDev);
        emit getCmd(xml);

        uiCmd * cmd = new uiCmd(this);
        connect(this, &uiHome::refrCmd, cmd, &uiCmd::refrCmd);
        connect(cmd, &uiCmd::setCmd, this, [=](QString xml){
            emit setCmd(xml);
            cmd->close();
            cmd->deleteLater();
        });

        cmd->exec();
    });

    // DNA
    connect(ui->actionDNS, &QAction::triggered, this, [=](){
        m_curLocalDev->setSn(ui->sn->text());

        // 读取信息
        ToolXml toolXml;
        QString xml = toolXml.makeGetDnaXml(m_curLocalDev);
        emit getDna(xml);

        uiDna * dna = new uiDna(this);
        connect(this, &uiHome::refrDna, dna, &uiDna::refrDna);
        connect(dna, &uiDna::setDna, this, [=](QString xml){
            emit setDna(xml);
            dna->close();
            dna->deleteLater();
        });

        dna->exec();
    });

    // 关于
    connect(ui->actionabout, &QAction::triggered, this, [=](){
        uiAbout * about = new uiAbout(this);
        about->setWindowFlags(Qt::Dialog);
        about->show();
    });
}

uiHome::~uiHome()
{
    qDebug() << "退出程序";

    if (m_work != nullptr)
    {
        this->m_work->deleteLater();
        m_work = nullptr;
    }
    if (m_t != nullptr)
    {
        this->m_t->quit();
        this->m_t->wait();
        this->m_t->deleteLater();
        m_t = nullptr;
    }

    delete ui;
}

void uiHome::on_seachCluster_clicked()
{
    if (!m_isConnect)
    {
        qDebug() << "打开搜索窗口";
        this->ui_search = new uiSeach();
        ui_search->move(this->x() + 10, this->y() - 10);

        connect(ui_search, &uiSeach::clusterConnect, this, &uiHome::tcpConnectCluster);

        ui_search->setWindowModality(Qt::ApplicationModal);
        ui_search->show();
    }
    else
    {
        homeInit();
    }
}

void uiHome::tcpConnectCluster(udpDeviceInfo_t dev)
{
    ui->seachCluster->setEnabled(false);
    this->ui_search = nullptr;

    // 实例化任务类
    this->m_work = new WorkTcp(dev);
    this->m_work->moveToThread(this->m_t);

    // 连接信号槽
    connect(this, &uiHome::tcpConnect, m_work, &WorkTcp::connectToCluster);

    connect(this, &uiHome::searchLocalDev, m_work, &WorkTcp::sendGetLocal);

    connect(m_work, &WorkTcp::clusterDisconnected, this, [=](){
        this->homeInit();
    });

    connect(m_work, &WorkTcp::clusterConnected, this, [=](QString sn){
        QMessageBox::information(this, "连接成功", "成功与簇控制器建立连接！");
        qDebug() << "TCP连接成功";
        ui->clusterInfo->setEnabled(true);
        ui->clusterBox->setEnabled(true);
        ui->sn->setText(sn);
        ui->seachCluster->setText("断开连接");
        this->m_isConnect = true;
    });

    connect(m_work, &WorkTcp::sendRetError, this, [=](int ret){
        qDebug() << QString("home ret: %1").arg(ret);
        retError(ret);
    });

    connect(m_work, &WorkTcp::msgbox, this, [=](QString title, QString content, int msgType, int ret){
        if (msgType == 0)
        {
            QMessageBox::information(this, title, content);
        }
        else if (msgType == 1)
        {
            QMessageBox::warning(this, title, QString("%1 (ret = %2)").arg(content).arg(ret));
        }
    });

    // 成功获取到簇控制器
    connect(m_work, &WorkTcp::getClusterSuccess, this, [=](Cluster * c){
        ui->seachCluster->setEnabled(true);

        this->m_clus = c;
        ui->actionSetCluster->setEnabled(true);
        ui->sn->setText(c->sn());
        ui->switchId->setText(c->switchId());
        ui->line->setText(c->line());
        ui->lineId->setText(c->lineId());
        ui->hdVer->setText(c->hwVer());
        ui->swVer->setText(c->swVer());
        for (int i = 0; i < c->m_localDev.size(); i++)
        {
            qDebug() << QString("local[%1] -->> bus: %2, addr: %3, offset: %4").arg(i).arg(c->m_localDev.at(i).busID()).arg(c->m_localDev.at(i).getMAddr()).arg(c->m_localDev.at(i).offset());
            if (c->m_localDev.at(i).busID() == 0)
            {
                ui->dropAddr->addItem(c->m_localDev.at(i).getMAddr());
            }
        }
    });

    // 成功获取到就地控制器
    connect(m_work, &WorkTcp::getLocalSuccess, this, [=](LocalDev * ld){
        ui->actionLocalReboot->setEnabled(true);
        ui->actionLocalReset->setEnabled(true);
        ui->actionSetLocal->setEnabled(true);

        this->m_curLocalDev = ld;

        ui->motorBox1->setEnabled(true);
        ui->motorBox2->setEnabled(true);
        ui->actionHMI->setEnabled(true);
        ui->actionCMD->setEnabled(true);
        ui->actionDNS->setEnabled(true);

        ui->row->setText(QString::number(ld->row()));
        ui->row->setText(QString::number(ld->col()));
        ui->col->setText(QString::number(ld->col()));
        ui->sector->setText(QString::number(ld->sector()));
        ui->hcdi->setText(QString::number(ld->hcdi()));

        ui->offset->setText(QString::number(ld->offset()));
        ui->hwVer->setText(ld->hwVer());
        ui->swVer_2->setText(ld->swVer());
        ui->swbTime->setText(ld->swbTime());
        ui->logLevel->setText(g_logLevel[ld->getLogLevel()]);
        ui->baudrate->setText(g_baudrate[ld->getBaudrate()]);

        refrMotor(m_curLocalDev);
    });

    // 读取cmd成功
    connect(m_work, &WorkTcp::getCmdSuccess, this, [=](LocalDev * local){
        localCmd_t cmd = local->getCmd();
        this->m_curLocalDev->setCmd(cmd);
        delete local;
        emit refrCmd(m_curLocalDev);
    });

    // 读取dna成功
    connect(m_work, &WorkTcp::getDnaSuccess, this, [=](LocalDev * local){
        localDna_t dna = local->getDna();
        this->m_curLocalDev->setDna(dna);
        delete local;
        emit refrDna(m_curLocalDev);
    });

    // 更新电机状态
    connect(m_work, &WorkTcp::motorRefrSuccess, this, [=](LocalDev * local){
        if (m_curLocalDev == nullptr)
            return;
        if (local->busID() == m_curLocalDev->busID()
                && local->getMAddr() == m_curLocalDev->getMAddr())
        {
            qDebug() << "refrMotor";
            m_curLocalDev->m_motor = local->m_motor;
            refrMotor(m_curLocalDev);
        }
    });

    // 设置电机
    connect(this, &uiHome::setMotor, m_work, &WorkTcp::setMotor);

    // 重启 重置就地控制器
    connect(this, &uiHome::clusterReboot, m_work, &WorkTcp::sendClusterReboot);

    // 设置就地控制器
    connect(this, &uiHome::setLocal, m_work, &WorkTcp::sendSetLocal);

    // 设置簇控制器
    connect(this, &uiHome::setCluster, m_work, &WorkTcp::sendSetCluster);

    // 设置CMD
    connect(this, &uiHome::getCmd, m_work, &WorkTcp::sendGetCmd);
    connect(this, &uiHome::setCmd, m_work, &WorkTcp::sendSetCmd);

    // 设置DNA
    connect(this, &uiHome::getDna, m_work, &WorkTcp::sendGetDna);
    connect(this, &uiHome::setDna, m_work, &WorkTcp::sendSetDna);

    // 启动子线程
    this->m_t->start();

    // 开始连接簇控制器
    emit tcpConnect();

    QTimer::singleShot(5000, this, [=](){
        if (!this->m_isConnect)
        {
            qDebug() << "网络连接超时！";
            QMessageBox::warning(this, "连接失败", "网络连接超时，请检查网络通信！");
            this->homeInit();
        }
    });
}

void uiHome::retError(int ret)
{
    switch (ret) {
    case 1:
        QMessageBox::warning(this, "错误",  QString("xml错误！(ret: %1)").arg(ret));
        break;
    case 2:
        QMessageBox::warning(this, "错误", QString("版本号太低！(ret: %1)").arg(ret));
        break;
    case 3:
        QMessageBox::warning(this, "错误", QString("不支持控制！(ret: %1)").arg(ret));
        break;
    case 4:
        QMessageBox::warning(this, "错误", QString("控制失败！(ret: %1)").arg(ret));
        break;
    case 5:
        QMessageBox::warning(this, "错误", QString("参数不匹配！(ret: %1)").arg(ret));
        break;
    case 6:
        QMessageBox::warning(this, "错误", QString("当前模式不允许修改！(ret: %1)").arg(ret));
        break;
    case 7:
        QMessageBox::warning(this, "错误", QString("数据格式不匹配！(ret: %1)").arg(ret));
        break;
    case 8:
        QMessageBox::warning(this, "错误", QString("接口不存在！(ret: %1)").arg(ret));
        break;
    case 10:
        QMessageBox::warning(this, "错误", QString("需要先登录！(ret: %1)").arg(ret));
        break;
    case 11:
        QMessageBox::warning(this, "错误", QString("重复登录！(ret: %1)").arg(ret));
        break;
    case 12:
        QMessageBox::warning(this, "错误", QString("设备uuid已添加！(ret: %1)").arg(ret));
        break;
    case 13:
        QMessageBox::warning(this, "错误", QString("参数不匹配！(ret: %1)").arg(ret));
        break;
    case 14:
        QMessageBox::warning(this, "错误", QString("设备uuid不存在(ret: %1)").arg(ret));
        break;

    default:
        break;
    }
}

void uiHome::on_clusterInfo_clicked()
{
    qDebug() << "查看详细信息";
    Cluster * c = this->m_work->getC();
    if (c->sn().size() == 0)
    {
        QMessageBox::information(this, "详细信息", "未能获取到簇控制器的信息...");
        return;
    }

    uiInfo * info = new uiInfo(c);
    info->setWindowModality(Qt::ApplicationModal);
    info->setGeometry(this->x() + 150, this->y() + 100, info->width(), info->height());
    info->show();
}

void uiHome::homeInit()
{
    if (m_isConnect)
        QMessageBox::information(this, "断开连接", "与簇控制器断开连接！");
    qDebug() << "TCP连接已断开";

    ui->sn->setText("");
    ui->switchId->setText("");
    ui->line->setText("");
    ui->lineId->setText("");
    ui->hdVer->setText("");
    ui->swVer->setText("");

    ui->seachCluster->setEnabled(true);

    ui->clusterInfo->setEnabled(false);
    ui->clusterBox->setEnabled(false);
    ui->motorBox1->setEnabled(false);
    ui->motorBox2->setEnabled(false);
    ui->actionLocalReboot->setEnabled(false);
    ui->actionLocalReset->setEnabled(false);
    ui->actionSetLocal->setEnabled(false);
    ui->actionHMI->setEnabled(false);
    ui->actionCMD->setEnabled(false);
    ui->actionDNS->setEnabled(false);
    ui->dropBus->setCurrentIndex(0);
    ui->dropAddr->clear();
    ui->seachCluster->setText("搜索");
    this->m_work->deleteLater();
    this->m_work = nullptr;
    this->m_isConnect = false;
}

void uiHome::ShowHMI()
{
    qDebug() << "show hmi";

    this->m_curLocalDev->setSn(ui->sn->text());
    uiHmi * hmi = new uiHmi(this->m_curLocalDev);
    hmi->setWindowModality(Qt::ApplicationModal);
    hmi->setGeometry(this->x() + 150, this->y() + 100, hmi->width(), hmi->height());

    connect(hmi, &uiHmi::setLocal, this, [=](QString xml){
        emit setLocal(xml);
    });

    hmi->show();
}

void uiHome::refrMotor(LocalDev *ld)
{
    ui->trip->setText(QString::number(ld->m_motor.at(0).trip()));
    ui->speed->setText(QString::number(ld->m_motor.at(0).speed()));
    ui->ei->setText(QString::number(ld->m_motor.at(0).ei()));
    ui->power->setText(QString::number(ld->m_motor.at(0).power()));
    ui->mode->setText(g_curMode[ld->m_motor.at(0).mode()]);
    ui->state->setText(QString::number(ld->m_motor.at(0).state()));
    ui->ioInput->setText(QString::number(ld->m_motor.at(0).ioInput()));
    ui->limitStop->setText(QString::number(ld->m_motor.at(0).limitSpos()));
    ui->errcode->setText(QString::number(ld->m_motor.at(0).errcode()));

    ui->trip_2->setText(QString::number(ld->m_motor.at(1).trip()));
    ui->speed_2->setText(QString::number(ld->m_motor.at(1).speed()));
    ui->ei_2->setText(QString::number(ld->m_motor.at(1).ei()));
    ui->power_2->setText(QString::number(ld->m_motor.at(1).power()));
    ui->mode_2->setText(g_curMode[ld->m_motor.at(1).mode()]);
    ui->state_2->setText(QString::number(ld->m_motor.at(1).state()));
    ui->ioInput_2->setText(QString::number(ld->m_motor.at(1).ioInput()));
    ui->limitStop_2->setText(QString::number(ld->m_motor.at(1).limitSpos()));
    ui->errcode_2->setText(QString::number(ld->m_motor.at(1).errcode()));


    this->m_motorRefrTime->setText(QString("电机状态更新时间：%1").arg(QDateTime::currentDateTime().toString("hh:mm:ss")));
}


void uiHome::on_dropBus_currentIndexChanged(int index)
{
    QVector<LocalDev> * ld = &this->m_work->getC()->m_localDev;

    ui->dropAddr->clear();
    for(int i = 0; i < ld->size(); i++)
    {
        if (ld->at(i).busID() == index)
        {
            ui->dropAddr->addItem(ld->at(i).getMAddr());
        }
    }
}

void uiHome::on_pushButton_3_clicked()
{
    int busId = ui->dropBus->currentIndex();
    QString maddr = ui->dropAddr->currentText();

    QVector<LocalDev> * ld = &this->m_work->getC()->m_localDev;
    int ldIndex = -1;
    for(int i = 0; i < ld->size(); i++)
    {
        if (ld->at(i).busID() == busId)
        {
            if (ld->at(i).getMAddr() == maddr)
            {
                ldIndex = i;
            }
        }
    }

    if (ldIndex >= 0)
    {
        emit searchLocalDev(ldIndex);
    }
    else
    {
        QMessageBox::warning(this, "获取失败", "获取就地传感器失败！");
    }


}

void uiHome::on_pushButton_4_clicked()
{
    uiSetMotor * set = new uiSetMotor(ui->sn->text(), m_curLocalDev, 0);
    set->setWindowModality(Qt::ApplicationModal);
    set->setGeometry(this->x() + 150, this->y() + 100, set->width(), set->height());
    set->setWindowTitle("主轴电机控制");

    connect(set, &uiSetMotor::setMotor, this, [=](QString xml){
        set->close();
        set->deleteLater();
        emit setMotor(xml);
    });

    set->show();
}

void uiHome::on_pushButton_5_clicked()
{
    uiSetMotor * set = new uiSetMotor(ui->sn->text(), m_curLocalDev, 1);
    set->setWindowModality(Qt::ApplicationModal);
    set->setGeometry(this->x() + 150, this->y() + 100, set->width(), set->height());
    set->setWindowTitle("副轴电机控制");

    connect(set, &uiSetMotor::setMotor, this, [=](QString xml){
        set->close();
        set->deleteLater();
        emit setMotor(xml);
    });

    set->show();
}

void uiHome::on_stop_clicked()
{
    ToolXml toolXml;
    QString xml = toolXml.makeSetMotor(ui->sn->text(), m_curLocalDev, 0, 1, 0, 0, 0, 0);
    emit setMotor(xml);
}

void uiHome::on_stop_2_clicked()
{
    ToolXml toolXml;
    QString xml = toolXml.makeSetMotor(ui->sn->text(), m_curLocalDev, 1, 1, 0, 0, 0, 0);
    emit setMotor(xml);
}
